#ifndef _VECTOR_
#define _VECTOR_

#include <iostream>
using namespace std;

template <typename Object>
class Vector
{
private:
    int theSize;//分配大小
    int theCapacity;//分配容量，vector一次分配一组内存，满了则增加
    Object* objects;

public:
    explicit Vector(int initSize = 0)//带参数的显示构造函数，允许自定义大小
	:theSize(initSize), theCapacity(initSize + SPARE_CAPACITY)//初始化列表，等同于在括号内写初始化，A(n)则容量为n+固值
    {
	objects = new Object [theCapacity];
    }
    Vector(const Vector& rhs): objects(NULL)//偷懒的复制构造函数
    {
	operator=(rhs);
    }
    ~Vector()//简单的析构函数
    {
	delete [] objects;
    }
    const Vector & operator = (const Vector& rhs)//=重载函数，注意内存泄漏
    {
	if(this != &rhs)
	{
	    delete [] objects;
	    theSize = rhs.size();//直接rhs.size即可？
	    theCapacity = rhs.theCapacity;

	    objects = new Object [capacity()];
	    for (int k = 0; k < size(); k++)//这里的size调用的是this的size，已经由thesize复制过来了
		objects[k] = rhs.objects[k];
	}
	return *this;
    }
    
    void resize(int newSize)//改大小，当超过容量时要改容量
    {
	if (newSize > theCapacity)
	    reserve(newSize * 2 + 1);//超出后以2x+1扩展，而与初始固值无关
	theSize = newSize;
    }
    void reserve(int newCapacity)//改容量
    {
	if (newCapacity < theSize)//如果新增容量不够大，忽略请求
	    return;
	Object *oldArray = objects;
	objects = new Object [newCapacity];
	for (int k = 0; k < theSize; k++)
	    objects[k] = oldArray [k];

	theCapacity = newCapacity;
	delete [] oldArray;
    }
    Object& operator [] (int index)//修改
    {
    	return objects[index];
    }
    const Object& operator [] (int index) const//访问
    {
        return objects[index];
    }
    bool empty() const
    {
	return size() == 0;
    }
    int size() const
    {
    	return theSize;
    }
    int capacity() const
    {
	return theCapacity;
    }
    void push_back(const Object& x)//末端push入
    {
	if (theSize == theCapacity)
	    reserve(2 * theCapacity + 1);
	objects[theSize++] = x;//旧的末端后一个（坐标为size）等于x后，size+1,小细节
    }
    void pop_back()//末端pop出（封装性，直接减size可达成效果，而没有删除元素，与delete不同，不造成泄漏）
    {
	theSize--;
    }
    const Object& back() const//读取末端
    {
	return objects[theSize-1];
    }

    //为了用户而统一接口格式
    typedef Object* iterator;
    typedef const Object* const_iterator;

    iterator begin()
    {
	return &objects[0];
    }
    const_iterator begin() const
    {
	return &objects[0];
    }
    iterator end()
    {
	return &objects[size()];
    }
    const_iterator end() const
    {
	return &objects[size()];
    }
    
    enum {SPARE_CAPACITY = 20};//枚举，替代多个define
};

#else
#endif
